/**
 * LookupServiceRegistry.java
 */
package fss.common;

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.List;
import java.util.logging.Logger;

import fss.core.config.FssConfigFactory;
import fss.core.config.ServiceRegistryConfig;
import fss.util.rmi.RmiId;

/**
 * This provides the capability to search for available Service Registry
 * according to the configuration file.
 * 
 * @author thinh
 *
 */
public class LookupServiceRegistry {
    /**
     * The logger for this class.
     */
    private final static Logger logger = Logger.getLogger(LookupServiceRegistry.class.getName());
    /**
     * Return the id of an available Service Registry.
     * @return the id.
     */
    public static RmiId lookup() {
        RmiId id = null;
        ServiceRegistryConfig config = FssConfigFactory.getInstance().getRegistryServerConfig();
        List<Integer> portList = config.getPortList();
        List<String> hostList = config.getHostList();
        
        for(String host : hostList) {
            for(int port : portList) {
                try {
                    logger.info("Checking for Service Registry at " + host + ":" + port);
                    Registry registry = LocateRegistry.getRegistry(host, port);
                    logger.info("Registry found at " + host + ":" + port + " with " + registry.list().length + " remote objects (Should only be 1).");
                    
                    // TODO: add some analysis logic
                    logger.info("!!!TODO: logic to determine if this Service Registry is best option!!!");
                    
                    if(registry.list().length == 1) {
                        String name = registry.list()[0];
                        id = new RmiId(host, name, port);
                        break;
                    }
                } catch (RemoteException e) {
                    // ignore, no service registry at host/port
                }
            }
        }        
        return id;
    }
}
